/* eslint-disable react/no-unused-state */
import React, { useState, useEffect } from 'react';
import './index.less';
import { Table, Form, Input, Button, Spin, Col, Row, Select } from 'antd';
import { FormattedMessage } from 'umi';
import { OperationEnum } from '@/utils/enum';
import { queryRule } from '../ListTableList/service';
import { exportOrderLog, templateCopy } from './service';
import CreateForm from './components/CreateForm';
import { TableItem } from './index.interface';

// type StateType = {
//     [propName: string]: any;
// };

// type ComponentsProps = {
//     [propName: string]: any;
// };

// interface _page {
//     props: ComponentsProps;
//     state: StateType;
// }

const TableList: React.FC<{}> = () => {
  const [list, setList] = useState([]);
  const [formDetail, setFormDetail] = useState({});
  const [listTotal, setListTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formType, setFormType] = useState('add');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRowList, setSelectedRowList] = useState([]);
  const [typeData, setTypeData] = useState([]);
  const [demovalue, setDemovalue] = useState('');
  const [query, setQuery] = React.useState({
    pageSize: 10,
    pageNum: 1,
  });

  const [form] = Form.useForm();
  // const { Option } = Select;

  // 获取数据
  async function getData() {
    console.log('query', query);
    setLoading(true);
    const data = await queryRule(query);
    setLoading(false);
    if (data.code === '2000') {
      console.log('data', data);
      const datalist = data.data.list.map((item: any, index: number) => {
        return { ...item, key: index + 1 };
      });
      console.log('datalist', datalist);
      setList(datalist);
      setListTotal(data.data.total);
    }
  }
  // 配置表格规则
  const columns = [
    {
      title: '车型代码',
      dataIndex: 'code',
      hideInSearch: true,
      width: 150,
      ellipsis: true,
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        },
      ],
    },
    {
      title: <FormattedMessage id="list.name" />,
      width: 150,
      dataIndex: 'name',
    },
    {
      title: '最大载重',
      dataIndex: 'maxWeight',
      width: 150,
      hideInSearch: true,
      // renderText: (val: string) => `${val} 万`,
    },
    {
      title: '最大装载体积',
      dataIndex: 'maxVolume',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '车厢内径长(M)',
      dataIndex: 'innerLength',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '车厢内径宽(M)',
      dataIndex: 'innerWidth',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '车厢内径高(M)',
      dataIndex: 'innerHeight',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '类型',
      width: 150,
      dataIndex: 'type',
      valueEnum: {
        0: { text: '关闭', status: 'Default' },
        1: { text: '运行中', status: 'Processing' },
        2: { text: '已上线', status: 'Success' },
        3: { text: '异常', status: 'Error' },
      },
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '最后修改人',
      width: 150,
      dataIndex: 'modifyUser',
      hideInSearch: true,
    },
    {
      title: '最后修改时间',
      width: 200,
      dataIndex: 'modifyTime',
      hideInSearch: true,
    },
  ];
  // 表单确认
  const onFinish = (values: any) => {
    setQuery({ ...query, ...values });
  };
  // 重置
  const onReset = () => {
    form.resetFields();
    console.log('form', form.getFieldsValue());
    const values = form.getFieldsValue();
    setQuery({ ...query, ...values, pageNum: 1 });
  };
  // 分页选择当前页
  const paginationChangePage = (page: any) => {
    setQuery({ ...query, pageNum: page });
  };
  // 表格选择事件
  const onSelectChange = (selectedKeys: any, selectedRows: any) => {
    console.log('selectedRowKeys changed: ', selectedKeys);
    console.log('selectedRows changed: ', selectedRows);
    setSelectedRowKeys(selectedKeys);
    setSelectedRowList(selectedRows);
  };

  const add = () => {
    handleModalVisible(true);
    setFormType(OperationEnum.add);
  };
  const edit = (row: TableItem) => {
    setFormDetail(row);
    handleModalVisible(true);
    setFormType(OperationEnum.edit);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const daoRu = () => {
    console.log('导入');
  };

  const daoChu = () => {
    console.log('导出');
    exportOrderLog(query);
  };

  const muban = () => {
    console.log('模板');
    templateCopy().then((res: any) => {
      if (res.code === '2000') {
        window.open(res.data);
      }
    });
  };

  useEffect(() => {
    getData();
    const data: any = [];
    for (let index = 0; index < 10000; index += 1) {
      data.push({
        code: index + 1,
        value: `name${index}`,
      });
    }
    setTypeData(data);
  }, [query, form]);

  return (
    <div>
      {/* 搜索查询栏 */}
      <div>
        <Form form={form} onFinish={onFinish}>
          <Row>
            <Col span={8}>
              <Form.Item label="车型代码" name="code" initialValue={null}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="车型名称" name="name" initialValue={null}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="类型" name="type" initialValue={null}>
                {/* 如果数据量过大，可以支持远程搜索，默认条件为空时，返回最多不超过1000条数据，通过模糊查找数据，通过接口返回实际筛选数据，防抖控制，并且不超过1000条 */}
                {/* select 自带大数据模式，参考api  options */}
                <Select
                  allowClear
                  showSearch
                  placeholder="Select province"
                  optionFilterProp="value"
                  filterOption={(input, option) => option?.value.indexOf(input) >= 0}
                  options={typeData}
                >
                  {/* {typeData.map((item: { code: number; name: string }) => (
                    <Option key={item.code} value={item.code}>
                      {item.name}
                    </Option>
                  ))} */}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          {/* 操作栏 */}
          <Row>
            <Col span={19}>
              <Button type="primary" onClick={() => add()}>
                新建
              </Button>
              <Button
                onClick={() => edit(selectedRowList[0])}
                disabled={selectedRowKeys.length !== 1}
              >
                修改
              </Button>
              <Button>删除</Button>
              <Button onClick={daoRu}>导入</Button>
              <Button onClick={daoChu}>导出</Button>
              <Button onClick={muban}>模板下载</Button>
            </Col>
            <Col span={5} style={{ textAlign: 'right' }}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button onClick={onReset}>重置</Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      {/* 表格 */}
      <Spin spinning={loading}>
        <Table
          rowSelection={rowSelection}
          pagination={{
            current: query.pageNum,
            pageSize: 10,
            total: listTotal,
            onChange: paginationChangePage,
          }}
          scroll={{ x: 1300, y: 600 }}
          dataSource={list}
          columns={columns}
        />
        ;
      </Spin>
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        detail={formDetail}
        modalVisible={createModalVisible}
        type={formType}
      />
    </div>
  );
};

export default TableList;
